﻿using AutoMapper;
using B.S.Base.Write.API.Application.Command;
using MediatR;
using WEBAPI.Damoin;
using WEBAPI.ErroeCode;
using WEBAPI.Indaseture.Infasetures;

namespace B.S.Base.Write.API.Application.CommandHandLer
{
    public class AddMenuCommandHandLer : IRequestHandler<AddMenuCommand, APIResult<object>>
    {

        private readonly IBaseRepostiy<MenuModel> menu;
        private readonly IMapper mapper;

        public AddMenuCommandHandLer(IBaseRepostiy<MenuModel> menu, IMapper mapper)
        {
            this.menu = menu;
            this.mapper = mapper;
        }
        public  Task<APIResult<object>> Handle(AddMenuCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();

            result.Code = ResultCode.Ok;
            result.Message = ResultCode.Ok.ToString();

            var count = menu.GetAll().Where(x => x.MenuName == request.MenuName && x.Pid == request.Pid && x.IsDeleted == false).Count();
            if (count > 0)
            {
                result.Code = ResultCode.Fail;
                result.Message = "添加失败，同一级菜单下名称不能重复";
                result.Data = "添加失败";
            }
            else
            {
                result.Data = "菜单添加成功";
                var entity = mapper.Map<MenuModel>(request);
                entity.CreateUserTime = DateTime.Now;
                if (request.Pid == 0)
                {
                    
                    entity.PmenuName = "";
                }
                else
                {
                    entity.PmenuName = menu.GetAll().FirstOrDefault(x => x.Id == request.Pid).MenuName;
                }
               
                menu.AddAsync(entity);

            }
            return Task.FromResult(result);
        }
    }
}
